/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.cezary.butler.walili.server.db.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.jdbc.core.PreparedStatementCreator;
import pl.cezary.butler.walili.server.db.tables.ITableDefinition;

/**
 *
 * @author czarek
 */
public class TableDefinitionUtils {
    
    private static final Logger log = Logger.getLogger(TableDefinitionUtils.class.getName());
    
    public static String generateParameters(final int count){
        if (count <= 0 ) return "";
        StringBuilder sb = new StringBuilder("?");
        for (int i = 1; i < count; ++i) {
            sb.append(", ?");
        }
        return sb.toString();
    }
    

    public static String getInsertQuery(ITableDefinition td) {        
        final String buffedQuery = String.format("INSERT INTO %s VALUES(%s)",td.getTable(),generateParameters(td.getColumns().length));
        log.log(Level.FINE,"Zapytanie insert {0}", buffedQuery);
        return buffedQuery;
    }

    public static PreparedStatementCreator getPreparedStatementCreator(final ITableDefinition table, final Object... parameters) {
        return new PreparedStatementCreator() {

            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                final PreparedStatement ps = con.prepareStatement(getInsertQuery(table));
                final ITableDefinition[] columns = table.getColumns();
                assert (columns.length >= parameters.length) : "Number of submited parameters must be lower of equal to number of columns";

                for (int i = 0; i < columns.length; ++i) {
                    final ITableDefinition column = columns[i];
                    ps.setObject(column.getColumnIndex(),
                            (i < parameters.length) ? parameters[i] : null,
                            column.getJdbcType());
                }
                return ps;
            }
        };
    }

    public static PreparedStatementCreator getPreparedStatementCreator(final Class<? extends ITableDefinition> table, final Object... parameters) {
        assert (table.isEnum());
        return getPreparedStatementCreator(table.getEnumConstants()[0], parameters);
    }
    
    public static String getQueryForColumn(ITableDefinition column){
        return String.format("SELECT %s FROM %s",column.toString(),column.getTable());
    }
    
    
}
